//
//  KLSearchViewController.m
//  used
//
//  Created by xalo on 16/7/19.
//  Copyright © 2016年 王凯. All rights reserved.
//

#import "KLSearchViewController.h"
#import <objc/runtime.h>


@interface KLSearchViewController ()<UITableViewDataSource,UITableViewDelegate, UISearchBarDelegate>

/** searchBar */
@property (nonatomic, strong) UISearchBar *searchBar;

/** 取消按钮 */
@property (nonatomic, strong) UIButton *cancelBtn;

@property (nonatomic, strong) UIView *bgSearchView;

@property (nonatomic, strong) UITableView *tableView;

/** 搜索记录 */
@property (nonatomic, strong) NSMutableArray *searchRecords;
@end

@implementation KLSearchViewController

- (NSMutableArray *)searchRecords {
    if (!_searchRecords) {
        _searchRecords = [NSMutableArray array];
    }
    return _searchRecords;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, kScreenW, kScreenH - 64)];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.dataSource = self;
        _tableView.delegate = self;
    }
    return _tableView;
}

- (UIView *)bgSearchView {
    if (!_bgSearchView) {
        _bgSearchView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 64)];
        _bgSearchView.backgroundColor = KLRGBColor(240, 240, 240);
        
    }
    return _bgSearchView;
}

- (UIButton *)cancelBtn {
    if (!_cancelBtn) {
        _cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _cancelBtn.frame = CGRectMake(CGRectGetMaxX(_searchBar.frame) + 20, 20, 40, 44);
        [_cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        [_cancelBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_cancelBtn addTarget:self action:@selector(cancelBtnAction) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _cancelBtn;
}

- (UISearchBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [[UISearchBar alloc] init];
        _searchBar.placeholder = @"请输入关键字";
        _searchBar.frame = CGRectMake(20, 20, kScreenW - 100, 44);
        _searchBar.searchBarStyle = UISearchBarStyleMinimal;
        _searchBar.delegate = self;
        UIImage* searchBarBg = [self GetImageWithColor:[UIColor whiteColor] andHeight:25.0f];
        //设置背景色
        [_searchBar setBackgroundColor:KLRGBColor(240, 240, 240)];
        //设置文本框背景
        [_searchBar setSearchFieldBackgroundImage:searchBarBg forState:UIControlStateNormal];
    }
    return _searchBar;
}

// 设置searchBar的textfield的颜色
- (UIImage*) GetImageWithColor:(UIColor*)color andHeight:(CGFloat)height
{
    CGRect r= CGRectMake(0.0f, 0.0f, 1.0f, height);
    UIGraphicsBeginImageContext(r.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, r);
    
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return img;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = KLRGBColor(220, 220, 220);

    self.navigationController.navigationBarHidden = YES;
    
    [self.view addSubview:self.bgSearchView];
    [self.bgSearchView addSubview:self.searchBar];
    [self.bgSearchView addSubview:self.cancelBtn];
    [self.view addSubview:self.tableView];
    

    self.tableView.sectionFooterHeight = 40;
    
    [self fetchRecords];
   
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.searchBar becomeFirstResponder];
}

- (void)fetchRecords {
    
    NSString *docuPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [docuPath stringByAppendingPathComponent:@"SearchRecord.plist"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
    }
    self.searchRecords = [NSArray arrayWithContentsOfFile:filePath].mutableCopy;
    if (self.searchRecords.count) {
        self.tableView.hidden = NO;
    }else {
        self.tableView.hidden = YES;
    }
}
- (void)cancelBtnAction {
    if ([self.delegate respondsToSelector:@selector(clickCancelBtn)]) {
        [self.delegate clickCancelBtn];
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}




#pragma mark - <UITableViewDataSource>


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.searchRecords.count == 0) return 0;
    return self.searchRecords.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.textLabel.text = self.searchRecords[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma mark - <UITabelViewDelegate>

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   
    
    NSString *docuPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [docuPath stringByAppendingPathComponent:@"SearchRecord.plist"];
    [self.searchRecords exchangeObjectAtIndex:indexPath.row withObjectAtIndex:0];
    [self.searchRecords writeToFile:filePath atomically:YES];
    
    // 请求数据
    if ([self.delegate respondsToSelector:@selector(passWord:)]) {
        [self.delegate passWord:self.searchRecords[0]];
    }
    
    [self.navigationController popViewControllerAnimated:NO];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *sepView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 40)];
    sepView.backgroundColor = [UIColor colorWithRed:220 green:220 blue:220 alpha:0.4];
    UIButton *clearBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 1, kWidth, 39)];
    [clearBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    clearBtn.backgroundColor = [UIColor whiteColor];
    clearBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [clearBtn setTitle:@"清除搜索记录" forState:UIControlStateNormal];
    [clearBtn addTarget:self action:@selector(clearRecords) forControlEvents:UIControlEventTouchUpInside];
    [sepView addSubview:clearBtn];
    return sepView;
}

- (void)clearRecords {
    [self.searchRecords removeAllObjects];
    self.tableView.hidden = YES;
    [self.tableView reloadData];
    NSString *docuPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [docuPath stringByAppendingPathComponent:@"SearchRecord.plist"];
    [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
}

#pragma mark - <UISearchBarDelegate>

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {

    if (self.tableView.isHidden) {
        self.tableView.hidden = NO;
    }
    
    NSString *docuPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [docuPath stringByAppendingPathComponent:@"SearchRecord.plist"];
    
    if ([self.searchRecords containsObject:searchBar.text]) {
        [self.searchRecords removeObject:searchBar.text];
    }
    [self.searchRecords insertObject:searchBar.text atIndex:0];
    [self.searchRecords writeToFile:filePath atomically:YES];
    [self.tableView reloadData];
    
    // 请求数据
    if ([self.delegate respondsToSelector:@selector(passWord:)]) {
        [self.delegate passWord:searchBar.text];
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - <UIScrollViewDelegate>
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
}
@end
